using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Reflection;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using THSLib;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Registrator;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Drawing;
using DevExpress.Accessibility;
using DevExpress.XtraEditors.ListControls;
using DevExpress.Data.Filtering;
using DevExpress.Data.Filtering.Helpers;
using THSERP.BusinessEntities;
namespace THSERP.BaseProvider
{


    public class THSLookUpListDataAdapter : LookUpListDataAdapter
    {
        public THSLookUpListDataAdapter ( THSRepositoryLookupEdit item )
            : base( item )
        {
        }

        protected override string CreateFilterExpression ( )
        {
            if ( string.IsNullOrEmpty( FilterPrefix ) )
            {
                return string.Empty;
            }
            string likeClause="%"+DevExpress.Data.Filtering.Helpers.LikeData.CreateStartsWithPattern( FilterPrefix );
            string lsFilterExp=new BinaryOperator( FilterField , likeClause , BinaryOperatorType.Like ).ToString();
            return lsFilterExp;
        }
    }

    [UserRepositoryItem( "RegisterCustomEdit" )]
    public partial class THSRepositoryLookupEdit :  DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit 
    {
        public string FieldGroup="";
        public string LookupTableName="";
        public THSGridControl OwnerGrid;
        public const string CustomEditName="THSLookupEdit";

        #region Make Search Contain
        static THSRepositoryLookupEdit ( )
        {
            RegisterCustomEdit();
        }


        public override string EditorTypeName
        {
            get { return "THSLookupEdit"; }
        }
 
        public static void RegisterCustomEdit ( )
        {

            EditorRegistrationInfo.Default.Editors.Add(
                                new EditorClassInfo( "THSLookupEdit" ,
                                typeof( THSLookupEdit ) , typeof( THSRepositoryLookupEdit ) , 
                                typeof( LookUpEditViewInfo ) , new ButtonEditPainter() , 
                                true , EditImageIndexes.LookUpEdit , typeof( PopupEditAccessible ) ) );
        }
      

        protected override LookUpListDataAdapter CreateDataAdapter ( )
        {
            return new THSLookUpListDataAdapter( this );
        }
        
        #endregion

        public THSRepositoryLookupEdit ( THSGridControl gridParent , string strLookupTableName )
        {

            this.LookupTableName=strLookupTableName;
            this.OwnerGrid=gridParent;

            InitDefaultProperties();


        }

        public THSRepositoryLookupEdit ( THSGridControl gridParent )
        {
            this.OwnerGrid=gridParent;
            InitDefaultProperties();
        }

        public THSRepositoryLookupEdit ( )
        {

            InitDefaultProperties();

        }

        public THSRepositoryLookupEdit ( IContainer container )
        {
            container.Add( this );

            InitDefaultProperties();

        }

        private void InitDefaultProperties ( )
        {
            this.AutoHeight=true;
            this.AutoSearchColumnIndex=0;
            this.ShowDropDown=DevExpress.XtraEditors.Controls.ShowDropDown.SingleClick;
            this.TextEditStyle=DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            this.HotTrackItems=true;
            SearchMode=DevExpress.XtraEditors.Controls.SearchMode.AutoFilter;

            CaseSensitiveSearch=false;
        }

        public void CheckAllowNewButton ( string strFieldGroup )
        {
            this.FieldGroup=strFieldGroup;
            if ( this.FieldGroup.Contains( "AllowNew" ) )
            {
                this.Properties.Buttons.AddRange(
                              new DevExpress.XtraEditors.Controls.EditorButton[] {
                                    new DevExpress.XtraEditors.Controls.EditorButton("btnNew", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)} );
                this.ButtonClick+=new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler( this.NewLookupEditObject_Click );

            }
        }


        protected Boolean _isRecentlyAddedObject=false;
        protected virtual void NewLookupEditObject_Click ( object sender , DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e )
        {
            //if ( e.Button.Tag=="btnNew" )
            //{



            //    Boolean isAllowNew = false;
            //    Boolean isAllowEdit = false;
            //    String strModuleName = "";
            //    foreach ( DevExpress.XtraNavBar.NavBarItem fldNavBar in THSApp.CurrentModule.ParentScreen.SectionManager.Items )
            //    {
            //        Regex re = new Regex( "allownew\\(.*\\)" , RegexOptions.IgnoreCase );
            //        MatchCollection matches = re.Matches( this.FieldGroup );

            //        if ( matches.Count > 0 )
            //        {
            //            string strTemp1 = fldNavBar.Tag.ToString( ).Trim( );
            //            if ( matches[0].Value.CompareTo( "AllowNew(" + strTemp1 + "Module)" ) == 0 )
            //            {
            //                strModuleName = fldNavBar.Tag.ToString( );
            //                isAllowNew = true;
            //            }
            //        }

            //        re = new Regex( "allowedit\\(.*\\)" , RegexOptions.IgnoreCase );
            //        matches = re.Matches( this.FieldGroup );

            //        if ( matches.Count > 0 )
            //        {
            //            string strTemp2 = fldNavBar.Tag.ToString( ).Trim( );
            //            if ( matches[0].Value.CompareTo( "AllowEdit(" + strTemp2 + "Module)" ) == 0 )
            //            {
            //                strModuleName = fldNavBar.Tag.ToString( );
            //                isAllowEdit = true;
            //            }
            //        }


            //    }



            //    guiNewObject _guiNewObject;
            //    Boolean isOpenModule=false;  

            //    if ( strModuleName != null )
            //        _guiNewObject = new guiNewObject( LookupTableName , isAllowNew , isAllowEdit , strModuleName ,null);
            //    else
            //        _guiNewObject = new guiNewObject( LookupTableName , isAllowNew , isAllowEdit , null , null );

            //    DialogResult objResult=_guiNewObject.ShowDialog();
            //    if ( objResult==DialogResult.Yes ) //Create object
            //    {
            //        DevExpress.XtraEditors.LookUpEdit lkeTemp=(DevExpress.XtraEditors.LookUpEdit)( this.OwnerGrid.DefaultView.ActiveEditor );
            //        lkeTemp.ShowPopup();
            //        lkeTemp.ClosePopup();
            //        lkeTemp.ItemIndex=( (IListSource)this.DataSource ).GetList().Count;
            //        this.DataSource=lkeTemp.Properties.DataSource;

            //    }
            //    else if ( objResult==DialogResult.No ) //openModule
            //    {

            //        _isRecentlyAddedObject=true;//  [7/28/2009 namtrung]
            //        ( (BaseModuleERP)this.OwnerGrid.Screen.Module ).InvokeControl=this;
            //        THSApp.ShowModule( strModuleName );
            //    }

            //}
           

        }


        // Module.ParentScreen.Actiivate() :  ->  lookupEdit.RefreshLastUpdateObject () 
        // Cap nhat object vua moi tao vao lookupedit
        public void RefreshLastUpdateObject ( )
        {
            if ( _isRecentlyAddedObject==true )
            {
                DevExpress.XtraEditors.LookUpEdit lkeTemp=(DevExpress.XtraEditors.LookUpEdit)( this.OwnerGrid.DefaultView.ActiveEditor );
                lkeTemp.ShowPopup();
                lkeTemp.ClosePopup();
                this.DataSource=lkeTemp.Properties.DataSource;

                int iRowIndex=GetRecentlyUpdateRow();
                if ( lkeTemp.ItemIndex!=iRowIndex )
                {
                    lkeTemp.ItemIndex=iRowIndex;
                    this._isRecentlyAddedObject=false;
                }

            }
        }


        private int GetRecentlyUpdateRow ( )
        {
            DateTime maxTime=DateTime.MinValue;
            int iRowIndex=-1;
           
            BaseBusinessController objLookupTableController= BusinessControllerFactory.GetBusinessController( this.LookupTableName+"Controller" );
            foreach ( DataRow dtRow in ( (DataSet)THSApp.LookupTables[this.LookupTableName] ).Tables[0].Rows )
            {
                BusinessObject objBusinessObject=(BusinessObject)objLookupTableController.GetObjectFromDataRow( dtRow );
                DateTime objDateTime=Convert.ToDateTime( THSDbUtil.GetPropertyValue( objBusinessObject , "AAUpdatedDate" ) );
                if ( objDateTime>maxTime )
                {
                    objDateTime=maxTime;
                    iRowIndex=( (DataSet)THSApp.LookupTables[this.LookupTableName] ).Tables[0].Rows.IndexOf( dtRow );
                }
            }
            return iRowIndex;
        }


     
    }
}
